<template>
  <div class="password-change">
    <el-card class="change-card">
      <template #header>
        <div class="card-header">
          <h3>修改密码</h3>
          <el-button @click="$router.back()">返回</el-button>
        </div>
      </template>

      <div class="change-content">
        <div class="security-tips">
          <el-alert
            title="安全提示"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <ul class="tips-list">
                <li>密码长度应为8-20位字符</li>
                <li>密码应包含字母和数字</li>
                <li>建议使用大小写字母、数字和特殊字符的组合</li>
                <li>不要使用过于简单或常见的密码</li>
              </ul>
            </template>
          </el-alert>
        </div>

        <el-form 
          ref="passwordFormRef" 
          :model="passwordForm" 
          :rules="passwordRules" 
          label-width="120px"
          class="password-form"
        >
          <!-- 当前密码 -->
          <el-form-item label="当前密码" prop="oldPassword">
            <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              placeholder="请输入当前密码"
              show-password
              autocomplete="current-password"
            />
          </el-form-item>

          <!-- 新密码 -->
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              show-password
              autocomplete="new-password"
              @input="checkPasswordStrength"
            />
            <!-- 密码强度指示器 -->
            <div v-if="passwordForm.newPassword" class="password-strength">
              <div class="strength-bar">
                <div 
                  class="strength-fill" 
                  :class="strengthClass"
                  :style="{ width: strengthPercentage + '%' }"
                ></div>
              </div>
              <span class="strength-text" :class="strengthClass">{{ strengthText }}</span>
            </div>
          </el-form-item>

          <!-- 确认新密码 -->
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
              autocomplete="new-password"
            />
          </el-form-item>



          <!-- 操作按钮 -->
          <el-form-item>
            <div class="form-actions">
              <el-button @click="resetForm">重置</el-button>
              <el-button type="primary" @click="changePassword" :loading="changing">
                确认修改
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 修改成功对话框 -->
    <el-dialog v-model="successDialogVisible" title="密码修改成功" width="400px" :close-on-click-modal="false">
      <div class="success-content">
        <el-icon class="success-icon" size="60" color="#67c23a">
          <SuccessFilled />
        </el-icon>
        <h3>密码修改成功！</h3>
        <p>您的密码已成功修改，请使用新密码登录。</p>
      </div>
      <template #footer>
        <div class="dialog-actions">
          <el-button type="primary" @click="goToLogin">重新登录</el-button>
          <el-button @click="goToProfile">返回个人中心</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { SuccessFilled } from '@element-plus/icons-vue'
import { changePassword as changePasswordAPI } from '@/api/userProfile'
import { useUserInfoStore } from '@/stores/userInfo'

const router = useRouter()
const userInfoStore = useUserInfoStore()

// 表单引用
const passwordFormRef = ref()

// 数据
const changing = ref(false)
const successDialogVisible = ref(false)

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码强度
const passwordStrength = ref(0)

// 表单验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, max: 20, message: '密码长度应为8-20位字符', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value && !/(?=.*[a-zA-Z])(?=.*\d)/.test(value)) {
          callback(new Error('密码应包含字母和数字'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 计算属性
const strengthPercentage = computed(() => {
  return passwordStrength.value * 25
})

const strengthText = computed(() => {
  const texts = ['', '弱', '中', '强', '很强']
  return texts[passwordStrength.value] || ''
})

const strengthClass = computed(() => {
  const classes = ['', 'weak', 'medium', 'strong', 'very-strong']
  return classes[passwordStrength.value] || ''
})

// 方法
const checkPasswordStrength = () => {
  const password = passwordForm.newPassword
  let strength = 0
  
  if (password.length >= 8) strength++
  if (/[a-z]/.test(password)) strength++
  if (/[A-Z]/.test(password)) strength++
  if (/\d/.test(password)) strength++
  if (/[^a-zA-Z\d]/.test(password)) strength++
  
  passwordStrength.value = Math.min(strength, 4)
}



const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    
    changing.value = true
    
    // 调用修改密码API
    const response = await changePasswordAPI({
      userId: userInfoStore.userInfo?.id || '', // 从用户状态获取当前登录用户ID
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })

    // 由于request拦截器已经处理了成功响应，这里直接处理成功逻辑
    successDialogVisible.value = true
    
  } catch (error) {
    if (error !== false) { // 不是表单验证错误
      ElMessage.error('密码修改失败')
      console.error('密码修改失败:', error)
    }
  } finally {
    changing.value = false
  }
}

const resetForm = () => {
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
  passwordStrength.value = 0
}

const goToLogin = () => {
  router.push('/login')
}

const goToProfile = () => {
  router.push('/user/profile/management')
}
</script>

<style scoped>
.password-change {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.change-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
}

.change-content {
  padding: 20px 0;
}

.security-tips {
  margin-bottom: 30px;
}

.tips-list {
  margin: 10px 0 0 20px;
  color: #606266;
}

.tips-list li {
  margin-bottom: 5px;
}

.password-form {
  max-width: 500px;
}

.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.strength-bar {
  flex: 1;
  height: 4px;
  background: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s;
}

.strength-fill.weak {
  background: #f56c6c;
}

.strength-fill.medium {
  background: #e6a23c;
}

.strength-fill.strong {
  background: #409eff;
}

.strength-fill.very-strong {
  background: #67c23a;
}

.strength-text {
  font-size: 12px;
  font-weight: bold;
}

.strength-text.weak {
  color: #f56c6c;
}

.strength-text.medium {
  color: #e6a23c;
}

.strength-text.strong {
  color: #409eff;
}

.strength-text.very-strong {
  color: #67c23a;
}

.verification-section {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.verification-desc {
  margin: 0 0 15px 0;
  color: #606266;
  font-size: 14px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.success-content {
  text-align: center;
  padding: 20px;
}

.success-content h3 {
  margin: 20px 0 10px 0;
  color: #303133;
}

.success-content p {
  color: #606266;
  margin-bottom: 20px;
}

.dialog-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
}
</style>
